package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.data.bean.response.UserInfoResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.databinding.ActIntegralExchangeBinding
import com.lykj.llw.box.ui.diafrg.IntegralExchangeSuccessDiaFrg
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 积分兑换
 * ================================================
 *
 * @author gosha
 * @date 2023/10/17-10:26
 */
class IntegralExchangeActivity : BaseActivity() {
    lateinit var binding: ActIntegralExchangeBinding

    private var mTextWatcher: TextWatcher? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActIntegralExchangeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        obtainIntegralInfo()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "积分兑换"
        binding.titleBar.tvRightOption.text = "兑换记录"

        FlowBus.with<String>("updatePtb").register(this){
            finish()
        }
    }

    //获取用户积分信息
    private fun obtainIntegralInfo() {
        RetrofitManager.instance.obtainUserInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, UserInfoResponse::class.java)

                binding.tvIntegral.text = "${bean.data?.integral}"
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { LogUtils.e("$msg") }
            }
        })
    }

    //积分兑换
    private fun integralExchange() {
        RetrofitManager.instance.integralExchange(binding.etPtbNum.text.toString(),
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@IntegralExchangeActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    obtainIntegralInfo()
                    IntegralExchangeSuccessDiaFrg()
                        .setPtb(binding.etPtbNum.text.toString().toInt())
                        .show(supportFragmentManager, "积分兑换弹窗")

                    binding.etPtbNum.setText("")
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@IntegralExchangeActivity, it)
                    }
                }
            })
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        mTextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (s?.length == 1 && s.equals("0")) {
                    s.delete(0, 1)
                } else {
                    binding.tvNeedIntegral.text = "所需积分:${s}0"
                }
            }
        }
        binding.etPtbNum.addTextChangedListener(mTextWatcher)

        binding.titleBar.tvRightOption.clickWithTrigger {
            startActivity(Intent(this, IntegralExchangeRecordActivity::class.java))
        }

        binding.tvBtnExchange.clickWithTrigger {
            if (binding.etPtbNum.text.isNullOrBlank()) {
                ToastUtils.showShort(this@IntegralExchangeActivity, "请输入要兑换的平台币数量")
                return@clickWithTrigger
            }

            integralExchange()
        }

        KeyboardUtils.registerSoftInputChangedListener(this) { height ->
            if (height == 0) {//软键盘收起,移除焦点
                binding.etPtbNum.clearFocus()
            }
        }
    }

    override fun onDestroy() {
        binding.etPtbNum.removeTextChangedListener(mTextWatcher)
        removeDisposables(this)
        super.onDestroy()
    }
}